package com.sgb.member.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberTypeBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.MemberBean;
import com.sgb.member.entity.MemberPersonBean;
import com.sgb.member.ui.activity.MemberCompanyWebActivity;
import com.sgb.member.ui.activity.MemberManageActivity;
import com.sgb.member.ui.adapter.MemberCommonAdapter;
import com.sgb.member.ui.adapter.MemberCommonPersonAdapter;
import com.sgb.member.view_model.MemberTypeModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class MemberTypeFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener
        , XChooseDialog.DialogCallBackImpl {
    @Inject
    MemberTypeModel mModel;
    private FragmentMemberTypeBinding mBind;
    /**
     * 会员主体
     */
    private String mNo0 = "1"; // 会员主体  // 类型 0个人 1企业 2团队
    /**
     * 会员主体
     */
    private String mNo01 = "1"; // type : 1需方会员 2供方会员
    /**
     * 会员类型
     */
    private String mNo1; // 会员类型
    /**
     * 企业类型
     */
    private String mNo3; // 企业类型

    private CommonPopEntity mAll;

    private MemberCommonAdapter myMemberAdapter;
    private MemberCommonPersonAdapter mPersonAdapter;
    private int mPosition;

    public MemberTypeFragment() {
    }

    public static MemberTypeFragment newInstance(int position, int cateType, CommonPopEntity entity) {
        MemberTypeFragment fragment = new MemberTypeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX", position);
        bundle.putInt("CATE_TYPE", cateType);
        bundle.putSerializable("CATE_OBJECT", entity);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBind = DataBindingUtil.inflate(inflater, R.layout.fragment_member_type, container, false);
        return mBind.getRoot();
    }

    @Override
    protected void initView() {
        if (getArguments() == null) return;
        mPosition = getArguments().getInt("INDEX", 0); // 界面下标
        initChooseDialog();
        initPopup();
        initRecycler();
        // 初始化筛选值
        int cateType = getArguments().getInt("CATE_TYPE", -1); // 会员分类跳转传输下标
        CommonPopEntity cateEntity = (CommonPopEntity) getArguments().getSerializable("CATE_OBJECT"); // 会员分类跳转传输筛选项
        if (cateEntity != null) {
            if (cateType == 0) { // 会员类型
                mNo1 = cateEntity.getNo();
                mBind.popup1.refreshChoose(mNo1, cateEntity.getTypeName(), cateEntity.getCurPos() + 1);
            }
        }

    }

    @Override
    protected void onLazyLoad() {
     //   loadData(false);
        loadOtherData();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData(false);
    }

    public void loadData(boolean isLoadMore) {
        String searchText = getActivity() == null ? "" : ((MemberManageActivity) getActivity()).getSearchText();
        switch (mPosition) {
            case 0:
                // 需方会员
                break;
            case 1:
                // 供方会员
                break;
            case 2:
                // 企业关注会员
                mModel.getMemberCompanys(isLoadMore, searchText, mNo0, mNo01, mNo1, mNo3);
                break;
            case 3:
                // 关注企业会员
                mModel.getMemberCustomers(isLoadMore, searchText, mNo0, mNo01, mNo1, mNo3);
                break;
        }
    }

    private boolean loadOtherData() {
        int[] cateType = {
//                PickCateType.TYPE_0, // 会员主体
                PickCateType.TYPE_01, // 供需方会员类型
                PickCateType.TYPE_1, // 会员类型
                PickCateType.TYPE_3, // 企业类型
        };
        boolean isLoadData = true;
        for (int key : cateType) {
            if (isListEmpty(key)) {
                // 除供方会员其余初始化默认都为需方会员  会员类型 0 供方 1需方
                mModel.getLeftChooseData(key, false, isDemandMember());
                isLoadData = false;
            }
        }
        return isLoadData;
    }

    /**
     * --------------------------------- Popup相关 -------------------------------------------------
     */
    public void initPopup() {
        // 企业关注会员 ： 经营地址隐藏，会员等级隐藏, 企业性质显示-隐藏，添加会员主体, 需方会员显示
        // 关注企业会员 ： 经营地址隐藏，会员等级隐藏, 企业性质显示-隐藏，添加会员主体, 需方会员显示
        mBind.popup0.setVisibility(View.GONE);
        mBind.popup2.setVisibility(View.GONE);
        mBind.popup4.setVisibility(View.GONE);
        mBind.popup1.setVisibility(View.VISIBLE);
        mBind.popup3.setVisibility(View.GONE);
        mBind.popup5.setVisibility(View.VISIBLE);

        mBind.popup2.setKeyName("企业类型");
        // 隐藏筛选
        mBind.chooseLayout.setVisibility(View.VISIBLE);
        mAll = new CommonPopEntity();
        mAll.setNo("");
        mAll.setTypeName("全部");
        mBind.popup0.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.popup1.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.popup2.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.popup3.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.popup5.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.chooseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean otherData = loadOtherData();
                if (otherData) {
                    refreshMemberMain(true, isPersonMember());
                }
            }
        });
    }

    /**
     * 是否需方会员
     */
    private boolean isDemandMember() {
        return TextUtils.equals("1", mNo01);
    }

    /**
     * 是否会员主体为 个人会员
     */
    private boolean isPersonMember() {
        return TextUtils.equals("0", mNo0);
    }

    // Popup 按照分类加载数据
    @Override
    public void onLoadChooseData(String mKeyName) {
        if (mKeyName.equals(mNameArray.get(PickCateType.TYPE_1))) { // 会员类型
            // 1需方会员 2供方会员 获取对应的会员类型
            mModel.getLeftChooseData(PickCateType.TYPE_1, false, isDemandMember());
        } else if (mKeyName.equals(mNameArray.get(PickCateType.TYPE_3))) { // 企业性质
            mModel.getLeftChooseData(PickCateType.TYPE_3, false, isDemandMember());
        } else if (mKeyName.equals(mBind.popup5.getKeyName())) { // "需方会员" 供方会员
            mModel.getLeftChooseData(PickCateType.TYPE_01, false, isDemandMember());
        } else if (mKeyName.equals(mBind.popup3.getKeyName())) { // 企业会员 个人会员
            mModel.getLeftChooseData(PickCateType.TYPE_0, false, isDemandMember());
        }
    }

    // Popup Item点击事件
    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        if (mKeyName.equals(mNameArray.get(PickCateType.TYPE_1))) {
            refreshItemValue(PickCateType.TYPE_1, position);
            updateMultiMemberSubType(PickCateType.TYPE_1, entity, position, false);
            loadData(false);
        } else if (mKeyName.equals(mNameArray.get(PickCateType.TYPE_3))) {
            // 企业类型
            refreshItemValue(PickCateType.TYPE_3, position);
            loadData(false);
        } else if (mKeyName.equals(mBind.popup5.getKeyName())) {
            // 需方会员
            if (!TextUtils.equals(entity.getNo(), mNo01)) {
                refreshItemValue(PickCateType.TYPE_01, position);
                updateMemberType(position, false);
                loadData(false);
            }
        } else if (mKeyName.equals(mBind.popup3.getKeyName())) {
            // 会员主体
            refreshMemberMain(false, TextUtils.equals("0", entity.getNo()));
            loadData(false);
        }
    }

    public void showLeftChooseDialog(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        mChooseDialog.addEntity(type, data);
        mChooseDialog.showDialog();
    }

    public void setLeftChooseData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        addMainEntity(type, data);
        switch (type) {
            case PickCateType.TYPE_0:
                // 会员主体
                mBind.popup3.setData(data);
                break;
            case PickCateType.TYPE_01:
                mBind.popup5.setData(data);
                break;
            case PickCateType.TYPE_1:
                mBind.popup1.setData(data);
                break;
            case PickCateType.TYPE_3:
                mBind.popup2.setData(data);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + type);
        }
    }

    public void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    public void addMainEntity(int index, String name, List<CommonPopEntity> list) {
        if (!TextUtils.isEmpty(name)) {
            mNameArray.put(index, name);
        }
        if (mData.get(index) != null) {
            mData.get(index).setTypeName(mNameArray.get(index));
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    /**
     * ------------------------------------ 侧滑刷选 ----------------------------------------
     */

    private XChooseDialog mChooseDialog;
    // 数据集
    private SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    private SparseArray<String> mNameArray;
    // 存储会员关联数据index
    private List<Integer> mMultiKey;
    private final String mMemberSubName = "会员子类";

    private void initChooseDialog() {
        mNameArray = new SparseArray<>();
//        mNameArray.put(PickCateType.TYPE_0, "会员主体");
        mNameArray.put(PickCateType.TYPE_01, "供需关系"); // 需方会员、供方会员
        mNameArray.put(PickCateType.TYPE_1, "会员类型");
        mNameArray.put(PickCateType.TYPE_2, mMemberSubName);
        mNameArray.put(PickCateType.TYPE_3, "企业类型");
        mMultiKey = new ArrayList<>();
        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) != null &&
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }

    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
        switch (entity.getSort()) {
            case PickCateType.TYPE_0: // 会员主体
                refreshMemberMain(true, TextUtils.equals("0", entity.getItemNo(pos)));
                break;
            case PickCateType.TYPE_01:
                updateMemberType(pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_1:
                updateMultiMemberSubType(entity.getSort(), entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            default:
                if (mMultiKey.contains(entity.getSort())) {
                    updateMultiMemberSubType(entity.getSort(), entity.getList().get(pos), pos, true);
                    mChooseDialog.showDialog();
                }
                break;
        }
    }

    private void updateMemberType(int pos, boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_1, tempList);
            for (Integer integer : mMultiKey) {
                mChooseDialog.addEntity(integer, mMemberSubName, tempList);
            }
        } else {
            addMainEntity(PickCateType.TYPE_1, tempList);
            for (Integer integer : mMultiKey) {
                addMainEntity(integer, mMemberSubName, tempList);
            }
        }
        mModel.getLeftChooseData(PickCateType.TYPE_1, isShowLeftDialog, pos == 0);
    }

    private void updateMultiMemberSubType(int sort, CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            for (Integer integer : mMultiKey) {
                if (sort < integer) {
                    mChooseDialog.addEntity(integer, mMemberSubName, tempList);
                }
            }
        } else {
            for (Integer integer : mMultiKey) {
                if (sort < integer) {
                    addMainEntity(integer, mMemberSubName, tempList);
                }
            }
        }
        if (pos > 0) {
            if (entity.getChildren() != null && entity.getChildren().size() > 0) {
                if (!entity.getChildren().get(0).getTypeName().equals("全部")) {
                    entity.getChildren().add(0, new CommonPopEntity("", "全部"));
                }
                int newSort = sort == PickCateType.TYPE_1 ? getMultiKey() : sort + 1;
                mMultiKey.add(newSort);
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(newSort, mMemberSubName, entity.getChildren());
                } else {
                    addMainEntity(newSort, mMemberSubName, entity.getChildren());
                }
            }
        }
    }

    private int getMultiKey() {
        return PickCateType.TYPE_2 * 10;
    }

    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        for (int i = 0; i < data.size(); i++) {
            int keyAt = data.keyAt(i);
            if (keyAt != PickCateType.TYPE_3) {
                mData.put(keyAt, data.get(keyAt));
            }
        }
        // mData = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        for (int i = 0; i < mData.size(); i++) {
            int key = mData.keyAt(i);
            refreshItemValue(key, mFilters.get(key));
        }
        loadData(false);
    }


    private void refreshItemValue(int key, int value) {
        XChooseEntity entity = mData.get(key);
        mFilters.put(key, value);
        String itemNo = entity.getItemNo(value);
        switch (key) {
            case PickCateType.TYPE_0: // 会员类型
                if (!TextUtils.equals(itemNo, mNo0)) {
                    mNo0 = itemNo;
                    mBind.popup3.refreshChoose(mNo0, entity.getItemName(value), value);
                }
                break;
            case PickCateType.TYPE_01: // 会员类型 ： 需方会员、供方会员
                if (!TextUtils.equals(itemNo, mNo01)) {
                    mNo01 = entity.getItemNo(value);
                    mBind.popup5.refreshChoose(mNo01, entity.getItemName(value), value);
                }
                break;
            case PickCateType.TYPE_1: // 会员类型
                if (!TextUtils.equals(itemNo, mNo1)) {
                    mNo1 = entity.getItemNo(value);
                    mBind.popup1.refreshChoose(mNo1, entity.getItemName(value), value);
                    mBind.popup1.setData(entity.getList(), mNo1);
                }
                break;
            case PickCateType.TYPE_3: // 企业类型
                String itemName = value == 0 ? "" : entity.getItemName(value);
                if (!TextUtils.equals(itemName, mNo3)) {
                    mNo3 = itemName;
                    mBind.popup1.refreshChoose(mNo3, entity.getItemName(value), value);
                }
                break;
            default:
                if (mMultiKey.contains(key) && value > 0) {
                    mNo1 = itemNo;
                }
                break;
        }
    }

    private void refreshMemberMain(boolean isShowDialog, boolean isPersonCompany) {
        SparseIntArray intArray = new SparseIntArray();
        if (isShowDialog) {
            SparseArray<XChooseEntity> mTemp = new SparseArray<>();
            if (isPersonCompany) {
                // 个人企业，过滤展示的选项
                for (int i = 0; i < mData.size(); i++) {
                    int keyAt = mData.keyAt(i);
                    //  企业类型
                    if (keyAt != PickCateType.TYPE_3) {
                        mTemp.put(keyAt, mData.get(keyAt));
                        intArray.put(keyAt, mFilters.get(keyAt));
                    } else {
                        intArray.put(keyAt, 0);
                    }
                }
                intArray.put(PickCateType.TYPE_0, 1);
                mChooseDialog.initData(mTemp, intArray);
            } else {
                mFilters.put(PickCateType.TYPE_0, 0);
                mChooseDialog.initData(mData, mFilters);
            }
            mChooseDialog.showDialog();
        } else {
            if (isPersonCompany) {
                // 个人
                mFilters.put(PickCateType.TYPE_0, 1);
            } else {
                mFilters.put(PickCateType.TYPE_0, 0);
            }
            result(mData, mFilters);
        }
    }


    @Override
    public void reset() {
        mFilters.clear();
        for (Integer integer : mMultiKey) {
            addMainEntity(integer, new ArrayList<>());
        }
        mMultiKey.clear();
        result(mData, mFilters);
        mChooseDialog.initData(mData, mFilters);
        mChooseDialog.showDialog();
    }

    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }

    /**
     * initRecycler
     */
    private void initRecycler() {
        TextView textView = mBind.emptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBind.recyclerView.setPullRefreshEnabled(true);
        mBind.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBind.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBind.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        if (isPersonMember()) {
            initPersonAdapter();
        } else {
            initCompanyAdapter();
        }
        mBind.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
    }

    private void initPersonAdapter() {
        mPersonAdapter = new MemberCommonPersonAdapter(getContext(), null, mPosition, null);
        mBind.recyclerView.setAdapter(mPersonAdapter);
        mPersonAdapter.setOnItemClick(new AdapterOnItemClick<MemberPersonBean>() {
            @Override
            public void onItemClick(MemberPersonBean memberPersonBean, int position) {
                if (!TextUtils.isEmpty(memberPersonBean.userNo)) {
                    MemberConfig.getInstance().startWebsiteInfo(getActivity(), memberPersonBean.userNo, 0);
                } else {
                    MToast.showToast(getActivity(), "个人No为空");
                }
            }
        });
        mPersonAdapter.setListener(new MemberCommonPersonAdapter.IFollowListener() {
            @Override
            public void onFollow(int pos, MemberBean bean) {
                mModel.userFocus(bean.getCompanyNo(), bean.isFocused(), pos);
            }
        });
    }

    private void initCompanyAdapter() {
        myMemberAdapter = new MemberCommonAdapter(getContext(), null, mPosition, null);
        mBind.recyclerView.setAdapter(myMemberAdapter);
        myMemberAdapter.setOnItemClick(new AdapterOnItemClick<MemberBean>() {
            @Override
            public void onItemClick(MemberBean memberBean, int position) {
                // 1供方会员 2需方会员
                if (isDemandMember()) {
                    memberBean.setMemberUpdateLeverType("2");
                } else {
                    memberBean.setMemberUpdateLeverType("1");
                }
                // MemberCompanyWebActivity.start(getActivity(), memberBean);
                if (!TextUtils.isEmpty(memberBean.getCompanyNo())) {
                    MemberConfig.getInstance().startWebsiteInfo(getActivity(), memberBean.getCompanyNo(), 1);
                } else {
                    MToast.showToast(getActivity(), "店铺No为空");
                }
            }
        });
        myMemberAdapter.setListener(new MemberCommonAdapter.IFollowListener() {
            @Override
            public void onFollow(int pos, MemberBean bean) {
                mModel.userFocus(bean.getCompanyNo(), bean.isFocused(), pos);
            }
        });
    }

    public void showEmpty() {
        mBind.recyclerView.setVisibility(View.GONE);
        mBind.emptyView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<MemberBean> list, boolean isLoadMore, boolean isLastPage) {
        mBind.recyclerView.setVisibility(View.VISIBLE);
        if (isLoadMore) {
            mBind.recyclerView.loadMoreComplete();
            if (list != null && list.size() > 0) {
                myMemberAdapter.addDatas(list);
            }
            mBind.recyclerView.setNoMore(isLastPage);
        } else {
            mBind.recyclerView.refreshComplete();
            if (list != null && list.size() > 0) {
                mBind.emptyView.setVisibility(View.GONE);
                myMemberAdapter.setDatas(list);
            } else {
                myMemberAdapter.clearDatas();
                mBind.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 已关注回调
     */
    @SuppressLint("NotifyDataSetChanged")
    public void updateMemberFollow(boolean isGz, int position) {
        myMemberAdapter.getDatas().remove(position);
        myMemberAdapter.notifyDataSetChanged();
    }
}
